package com.csl.xm.demo.controller;

import com.csl.xm.demo.base.controller.BaseController;
import com.csl.xm.demo.base.utils.StateParameter;
import com.csl.xm.demo.entity.User;
import com.csl.xm.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.csl.xm.demo.base.utils.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * 描述：用户控制器
 * </pre>
 *
 * @类名：com.csl.xm.demo.controller.UserController
 * @作者： 1410HL0236
 * @创建日期: 2019/11/20 13:32
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
  @Autowired
  UserService userService;

  @PostMapping("/add")
  @ResponseBody
  public ModelMap add(User user){
    try {
      if(StringUtils.isEmpty(user.getId())){
        user.setId(StringUtils.getUUID());
      }else{
        user.setUpdateDate(new Date());
      }
      userService.save(user);
      logger.info("保存成功");
      return getModelMap(StateParameter.SUCCESS,user, "保存成功");
    }catch (Exception e){
      e.printStackTrace();
      return getModelMap(StateParameter.FAULT,null, "保存失败");
    }

  }

  @GetMapping(value = "/delete")
  @ResponseBody
  public ModelMap delete(String id){
    try {
      User user = userService.findById(id);
      if(user == null){
        return getModelMap(StateParameter.SUCCESS,null,"找不到该用户");
      }
      userService.delete(user);
      return getModelMap(StateParameter.SUCCESS,null,"删除成功");

    }catch (Exception e){
      e.printStackTrace();
      return getModelMap(StateParameter.SUCCESS,null,"删除失败");
    }

  }

  @RequestMapping(value = "/list")
  public String view(HttpServletRequest request){
    List<User> list = userService.findAll();
    request.setAttribute("list",list);
    logger.info("返回列表");
    return "/demoPage/listPage";
  }

}
